<?php

namespace App\Http\Controllers\Article;

use App\Events\Comment;
use App\Http\Controllers\BaseController;
use App\Models\ArticleComment;
use Illuminate\Http\Request;

class CommentController extends BaseController
{
    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'parent_id' => 'integer',
            'article_id' => 'required|integer'
        ]);

        $user_id = auth('api')->id();
        $query = ArticleComment::query()
            ->with('user')
            ->selectRaw('article_comments.*,
            (select count(id) from user_like_article_comments where status=1 and user_id='.$user_id.' and article_comment_id=article_comments.id) as is_like,
            (select count(user_id) from user_like_article_comments where status=1 and article_comment_id=article_comments.id) as like_count')
            ->withCount('son')
            ->where(['article_id' => $param['article_id'],'audit_status' => 2]);

        $query->where('parent_id',$param['parent_id'] ?? 0);


        $comments = $query->orderByDesc('id')
                         ->simplePaginate();


        return $this->success($comments);

    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'parent_id' => 'integer',
            'content' => 'required|max:600',
            'image' => 'string',
            'article_id' => 'required|integer'
        ]);

        $param['user_id'] = auth('api')->id();

        $comment = ArticleComment::query()->create($param);

        if ($comment->getKey()){

            event(new Comment($comment->user_id));
            return $this->success('评论成功');
        }

        return  $this->error('评论失败');
    }


    public function delete(Request $request)
    {
        $param = $this->validate($request,[
            'comment_id' => 'required|integer'
        ]);

        $result = ArticleComment::query()->where('id',$param['comment_id'])->delete();

        return $result ? $this->success('删除成功') : $this->error('删除失败');
    }

}
